using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using XenoGears.Functional;
using AssertionHelper=XenoGears.Assertions.AssertionHelper;

namespace Jink.Core.Json.Values
{
    public class JsonArray : JsonValue
    {
        public JsonArray(IEnumerable<JsonValue> array)
            : this(array.ToArray())
        {
        }

        public JsonArray(params JsonValue[] array)
            : base(array.Select((el, i) => Tuple.Create(el, i)).ToDictionary(kvp => kvp.Item2.ToString(), kvp => kvp.Item1))
        {
        }

        public override void BuildCompactString(TextWriter writer)
        {
            writer.Write(String.Format("[{0}]", this.Select((kvp, i) =>
            {
                AssertionHelper.AssertTrue((kvp.Key == i.ToString()));
                return kvp.Value.ToCompactString();
            }).StringJoin(",")));
        }

        public override void BuildPrettyString(IndentedTextWriter writer)
        {
            writer.WriteLine();
            writer.WriteLine("[");
            writer.Indent++;
            this.ForEach(kvp => (kvp.Value ?? new JsonExpression("null")).BuildPrettyString(writer));
            writer.Indent--;
            writer.Write("]");
        }
    }
}